﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Com.FirstSolver.Splash;
using Ioacp.Library.Helpers;
using Mina.Core.Session;
using Mina.Filter.Codec;
using Mina.Transport.Socket;
using Com.FirstSolver.Splash;

namespace Ioacp.Hanvon
{
    /// <summary>
    /// 汉王 - 人证核验终端
    /// 型号: M0816
    /// </summary>
    public class HanvonSDK2
    {
        //private AsyncSocketAcceptor TcpServer = null;//修改处

        //Todo

        private TcpListenerPlus TcpServer = null;

        private const int DeviceCodePage = 936;

        private bool IsServerRunning = false;       // 服务器是否已运行
        private ushort _tcpPort = 9910;                // 服务端端口号
        private ushort _udpPort = 9911;             // Udp 端口
        private string _IpAddress = "";

        // 人证识别事件
        public event EventHandler<HanvonRecivedEventArgs> OnFaceCardDetectionChanged;

        // Session 会话打开
        private event EventHandler<dynamic> OnSessionOpened;

        public event EventHandler<dynamic> OnExecSync;

        public IoSession Session { get; set; }

        /// <summary>
        /// 最后一次收到数据的时间
        /// </summary>
        public DateTime LastRecTime { get; set; }

        #region Init

        /// <summary>
        /// 服务端端口号
        /// </summary>
        /// <param name="port"></param>
        public void Init(HanvonInitEventArgs e)
        {
            _tcpPort = e.TcpServerPort;
            _IpAddress = e.IpAddress;
            _udpPort = (ushort)(_tcpPort + 1);
        }

        #endregion

        #region Start

        /// <summary>
        /// 服务开始运行
        /// </summary>
        public void Start()
        {
            if (IsServerRunning) return;

            try
            {

                TcpServer = new TcpListenerPlus(IPAddress.Parse(_IpAddress), Convert.ToInt32(_tcpPort), false);
                TcpServer.OnServerTaskRequest += OnServerTaskProcess;

                // 启动侦听
                TcpServer.StartListenThread(null, 0, 10 * 60 * 1000);
            }
            catch (Exception ex)
            {
                LogEx.Error("汉王服务端接收启动", ex);
            }
        }

        private void OnServerTaskProcess(object sender, EventArgs e)
        {
            NetworkStreamPlus Stream = (NetworkStreamPlus)sender;

            string SerialNumber;    // 设备序列号
            while (true)
            {
                try
                {
                    string Answer;
                    Stream.Read(out Answer, DeviceCodePage);

                    // 显示接收字符串

                    if (Answer.StartsWith("PostRecord"))
                    {
                        // 提取序列号并保存
                        SerialNumber = FaceId_Item.GetKeyValue(Answer, "sn");

                        // 答复已准备好接收考勤记录

                        Stream.Write("Return(result=\"success\" postphoto=\"true\")", DeviceCodePage);

                    }
                    else if (Answer.StartsWith("Record"))
                    {   // 读取考勤记录
                        if (Answer != "")
                        {
                            string[] a = Answer.Split('\"');
                            HanvonReceiveInfo _hanvonri = new HanvonReceiveInfo();
                            if (a[7] == "face")
                            {
                                _hanvonri = new HanvonReceiveInfo { id = a[1].ToString(), name = a[3].ToString(), capturejpg = a[9] };
                            }
                            else
                            {
                                _hanvonri = new HanvonReceiveInfo { id = a[1].ToString(), name = a[3].ToString(), capturejpg = a[7] };
                            }
                            OnFaceCardDetectionChanged?.Invoke(this, new HanvonRecivedEventArgs { IpAddress = _IpAddress, Data = _hanvonri });
                        }
                        Stream.Write("Return(result=\"success\")", DeviceCodePage);   // 答复数据接收成功

                    }
                    else if (Answer.StartsWith("PostEmployee"))
                    {   // 准备上传人员
                        Stream.Write("Return(result=\"success\")", DeviceCodePage);
                    }
                    else if (Answer.StartsWith("Employee"))
                    {   // 接收人员数据
                        Stream.Write("Return(result=\"success\")", DeviceCodePage);   // 答复数据接收成功
                    }
                    else if (Answer.StartsWith("GetRequest"))
                    {   // 下发命令

                    }
                    else if (Answer.StartsWith("Quit"))
                    {   // 连接断开
                        break;
                    }
                }
                catch (System.Net.Sockets.SocketException)
                {   // 套接字关闭                    
                    break;
                }
                catch (System.IO.IOException)
                {   // 套接字关闭
                    break;
                }
                catch (System.ObjectDisposedException)
                {   // 套接字关闭
                    break;
                }
                catch (Exception ex)
                {
                    string ErrorMessage = "错误信息：" + ex.GetType().Name;
                }
            }
        }
        #endregion

    }
}